//
//  LoginViewWithOAUTHViewController.swift
//  CSYMicroBlockSina
//
//  Created by 姚彦兆 on 15/11/9.
//  Copyright © 2015年 姚彦兆. All rights reserved.
//

import UIKit

import SVProgressHUD

import AFNetworking

class LoginViewWithOAUTHViewController: UIViewController {

    let webView : UIWebView = UIWebView()
    
    override func loadView() {
        
        view = webView
        
        webView.delegate = self
        
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        setUpUI()

        loadWebRequest()
        
        // Do any additional setup after loading the view.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

}

extension LoginViewWithOAUTHViewController{

    private func loadWebRequest(){
    
        let urlStr = "https://api.weibo.com/oauth2/authorize?" + "client_id=" + client_id + "&redirect_uri=" + redirect_uri
    
        let request = NSURLRequest(URL: NSURL(string: urlStr)!)
        
        webView.loadRequest(request)
    
    }

}


// MARK: - 界面的设置
extension LoginViewWithOAUTHViewController{

    private func setUpUI () {
    
        //print("setUpUI")
        
        self.navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭", style: UIBarButtonItemStyle.Plain, target: self, action: "closeWebView")
        
        self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动获取", style: UIBarButtonItemStyle.Plain, target: self, action: "autoInput")
    
    }
    
    @objc private func autoInput(){
    
        let js = "document.getElementById('userId').value = '18636706784';" + "document.getElementById('passwd').value = '15343577589Yyz';"

        webView.stringByEvaluatingJavaScriptFromString(js)
    
    }
    
    func closeWebView (){
    
        dismissViewControllerAnimated(true) { () -> Void in
            
            //print("Complete")
            
        }
    
    }

}

// MARK: - 代理获得请求的URL
extension LoginViewWithOAUTHViewController : UIWebViewDelegate{

    func webViewDidStartLoad(webView: UIWebView) {
        
        //开始载入的时候调用
        
        SVProgressHUD.showWithStatus("请求授权中", maskType: SVProgressHUDMaskType.Black)
        
    }
    
    func webViewDidFinishLoad(webView: UIWebView) {

        //结束载入的时候调用
        SVProgressHUD.dismiss()
        
    }
    
    func webView(webView: UIWebView, didFailLoadWithError error: NSError?) {
        
        //载入出错的时候调用
        
        //print("----------->\(error)")
        
    }
    
    /*抓取到了网络请求
    
    <NSMutableURLRequest: 0x7fde51e11180> { URL: https://api.weibo.com/oauth2/authorize?client_id=641602405&redirect_uri=http://neihanshequ.com }
    LoadSuccess
    <NSMutableURLRequest: 0x7fde540d1560> { URL: https://api.weibo.com/oauth2/authorize }
    <NSMutableURLRequest: 0x7fde51e54660> { URL: https://api.weibo.com/oauth2/authorize# }
    <NSMutableURLRequest: 0x7fde51e593e0> { URL: https://api.weibo.com/oauth2/authorize }
    <NSMutableURLRequest: 0x7fde51e63580> { URL: http://neihanshequ.com/?code=6fdc3dfc4cf63982fec4812d55c82e38 }
    <NSMutableURLRequest: 0x7fde51ea1ef0> { URL: http://m.neihanshequ.com/ }
    <NSMutableURLRequest: 0x7fde540d3cd0> { URL: http://m.neihanshequ.com/?skip_guidence=1 }
    
    */
    
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
        //监听WebView的所有网络请求
        
        //如果网页没有获取到有用的请求信息,则拦截一切活动
        guard let urlStr = request.URL?.absoluteString else{
        
            //print(request.URL)
            
            print("WebView闲置")
            
            return false
        
        }
        
        //如果授权请求正在执行 ---> 让他继续
        if urlStr.hasPrefix("https://api.weibo.com/") {
        
            //print(request.URL)
            
            //print("[请求授权中...]")
            return true
            
        }
        
        //如果得到了定义好的域名请求,则代表或取到了自己的code ---> 获得数据[拦住他,不要继续了]
        if !urlStr.hasPrefix(redirect_uri) {
            
            //print("[拦截到CODE_URL]\(urlStr)")
            return false
        
        }
        
        //程序在获得了code之后被卡住了,执行后续的操作
        guard let queryStr = request.URL?.query else {
        
            return false
        
        }
        
        let str = "code="
        
        code = queryStr.substringFromIndex(str.endIndex)
        
        print("--->获得CODE<--- [\(code)]")
        
        //封装好的数据获取
        GetUserInfoModel().getTokenWithCode(code!) { (errorMessage) -> () in
            
            self.dismissViewControllerAnimated(true, completion: { () -> Void in
                
                SVProgressHUD.dismiss()
                
                NSNotificationCenter.defaultCenter().postNotificationName(APPDELEGATESHOULDSWITCHROOTVIEWCONTROLLER, object: "welCome")
                
            })
            
        }
        
        return true
        
    }

}
























